const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const app = express();

// Middleware to get client IP address
app.use((req, res, next) => {
  const ipAddress =
    req.headers['x-forwarded-for'] ||
    req.socket.remoteAddress ||
    'unknown_ip';
  req.clientIp = ipAddress;
  next();
});

function sanitizeIp(ip) {
  return ip.replace(/[:.]/g, '_');
}

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const sanitizedIp = sanitizeIp(req.clientIp);
    const uploadPath = path.join(__dirname, 'uploads', sanitizedIp);

    fs.mkdir(uploadPath, { recursive: true }, (err) => {
      if (err) {
        console.error('Error creating directory', err);
        return cb(err);
      } else {
        cb(null, uploadPath);
      }
    });
  },
  filename: function (req, file, cb) {
    const uploadDir = path.join(__dirname, 'uploads', sanitizeIp(req.clientIp));
    const originalName = file.originalname;
    const ext = path.extname(originalName);
    const baseName = path.basename(originalName, ext);
    let fileName = originalName;
    let counter = 1;

    // Synchronous check for existing files
    while (fs.existsSync(path.join(uploadDir, fileName))) {
      fileName = `${baseName}_${counter}${ext}`;
      counter++;
    }

    cb(null, fileName);
  }
});

const upload = multer({ storage: storage });

app.post('/upload', upload.single('file'), (req, res) => {
  res.status(200).send('File uploaded successfully');
});

app.use(express.static(__dirname));

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server started on port ${PORT}`);
});
